package com.unknownman.block.rabbitmq.send;


import com.lianziyou.chain.common.utils.RabbitMetaMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.UUID;

/**
 * 消息发送者
 */

@Slf4j
public class RabbitSender {
	
	@Autowired
    RabbitTemplate rabbitTemplate;

	@Value("${spring.application.group:}")
    private String groupName;


	

    /**
     * 发送MQ消息
     * @param rabbitMetaMessage Rabbit元信息对象，用于存储交换器、队列名、消息体
     * @return 消息ID
     */
    public String send(RabbitMetaMessage rabbitMetaMessage) throws Exception {
        final String msgId = UUID.randomUUID().toString();
        try {
            log.info("发送消息，msgId：{},{}",msgId,rabbitMetaMessage.getPayload());
            rabbitTemplate.convertAndSend(groupName + rabbitMetaMessage.getExchange(), groupName + rabbitMetaMessage.getRoutingKey(),
                    rabbitMetaMessage.getPayload(), new CorrelationData(msgId));
            return msgId;
        } catch (AmqpException e) {
            throw new RuntimeException("发送RabbitMQ消息失败！", e);
        }
    }

}
